package com.vip.common.exception;

import com.vip.common.response.ErrorCode;
import com.vip.common.response.RestResponse;
import com.vip.common.response.RestResponses;
import com.vip.common.util.EmptyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 全局异常处理，捕获所有Controller中抛出的异常。
 *
 * @author wgb
 * @date 2019/7/19
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 请求异常
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class, MissingServletRequestParameterException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public RestResponse<String> httpRequestException(Exception e) {
        log.error("请求异常 = {}", e.getMessage(), e);
        return RestResponses.newFailResponse(ErrorCode.METHOD_ERROR, e.getMessage());
    }

    /**
     * RequestParam等单参数验证拦截
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public RestResponse<String> constraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        StringBuilder sb = new StringBuilder();
        if (EmptyUtils.listIsEmpty(constraintViolations)) {
            for (ConstraintViolation<?> constraintViolation : constraintViolations) {
                sb.append(constraintViolation.getMessage()).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        log.error("参数异常 = {}", sb.toString(), e);
        return RestResponses.newFailResponse(ErrorCode.INVALID_PARAMETER, e.getMessage());
    }


    /**
     * RequestBody请求体验证拦截
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public RestResponse<String> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        if (bindingResult.hasErrors()) {
            for (ObjectError error : bindingResult.getAllErrors()) {
                sb.append(error.getDefaultMessage()).append(",");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        log.error("参数异常 = {}", sb.toString(), e);
        return RestResponses.newFailResponse(ErrorCode.INVALID_PARAMETER, e.getMessage());
    }

    /**
     * 文件上传限制异常
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public RestResponse<String> maxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        log.error("文件上传限制异常 = {}", e.getMessage(), e);
        return RestResponses.newFailResponse(ErrorCode.INVALID_PARAMETER, "文件大小超出上传限制, 请压缩或降低文件质量!");
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public RestResponse<String> businessException(BusinessException e) {
        log.error("业务异常 = {}", e.getMessage(), e);
        return RestResponses.newFailResponse(ErrorCode.BIZ_ERROR, e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public RestResponse<String> exceptionHandler(Exception e) {
        log.error("系统异常", e);
        return RestResponses.newFailResponse(ErrorCode.SYS_ERROR, "系统错误");
    }
}
